package com.secneo.appshare.activities;

import weibo4android.Weibo;
import weibo4android.WeiboException;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import com.secneo.appshare.AppShareApplication;
import com.secneo.appshare.R;
import com.secneo.appshare.api.impl.RemoteApiImpl;
import com.secneo.appshare.common.ActivityUtil;
import com.secneo.appshare.common.Constants;
import com.secneo.appshare.threads.LoginWeiboThread;
import com.secneo.mp.api.database.DatabaseHelper;

public class LoginWeiboMethodActivity extends Activity implements OnClickListener
{
	private EditText mAccountEditText;
	private EditText mPasswordEditText;
	private CheckBox mTellFansCheckBox;
	private CheckBox mAttOfficialCB ;
	private ProgressDialog mProgressDialog;
	private Button mLogin;
	private TextView mRegistSinaWbTV ;
	private int exit_behavior;

	private Handler handler = new Handler()
	{
		@Override
		public void handleMessage(Message msg)
		{
			mProgressDialog.dismiss();
			switch (msg.what)
			{
				case Constants.MSG_LOGIN_FAILED:
					ActivityUtil.alert(LoginWeiboMethodActivity.this, "微博登录失败");
					break;
					
				case Constants.MSG_LOGIN_SUCCESS:
					Bundle data = msg.getData() ;
					boolean first_login = data.getBoolean("first_login") ;
					if(Constants.EXIT_BEHAVIOUR_GOTO_MAIN==exit_behavior){		
						if(first_login){
							Intent intent = new Intent(LoginWeiboMethodActivity.this, UserInfoActivity.class);
							Bundle mBundle = new Bundle(); 
							mBundle.putInt("sns_type", Constants.SNS_INDEX_SINA);
							intent.putExtras(mBundle);
							startActivity(intent);
						} else {
							Intent intent = new Intent(LoginWeiboMethodActivity.this, ChooseUserActivity.class);
							Bundle mBundle = new Bundle(); 
							mBundle.putInt("sns_type", Constants.SNS_INDEX_SINA);
							intent.putExtras(mBundle);
							startActivity(intent);
						}						
					}
					else if(Constants.EXIT_BEHAVIOUR_BACK==exit_behavior){
						Intent intent = new Intent(LoginWeiboMethodActivity.this, ChooseUserActivity.class);
						Bundle mBundle = new Bundle(); 
						mBundle.putInt("sns_type", Constants.SNS_INDEX_SINA);
						intent.putExtras(mBundle);
						startActivity(intent);
						
					}
					else if(Constants.EXIT_BEHAVIOUR_GOTO_ZONE==exit_behavior){
						Intent intent = new Intent(LoginWeiboMethodActivity.this, ChooseUserActivity.class);
						Bundle mBundle = new Bundle(); 
						mBundle.putInt("sns_type", Constants.SNS_INDEX_SINA);
						intent.putExtras(mBundle);
						startActivity(intent);
					}
					
					
					
					if(mAttOfficialCB.isChecked()){
						//关注安卓分享官方微博
						Thread thread = new Thread(){
							public void run(){
								Weibo weibo = new Weibo() ;
								SharedPreferences sp = LoginWeiboMethodActivity.this.getSharedPreferences(Constants.PRE_USER_INFO, 0);
								String token = sp.getString(Constants.ACCESS_TOKEN, "") ;
								String secret = sp.getString(Constants.ACCESS_TOKEN_SECRET, "") ;
								weibo.setToken(token , secret) ;
								try {
									//如果已经关注会报错，不过已经关注了就不管了。
									weibo.createFriendshipByUserid(Constants.OFFICIAL_WEIBO_ID) ;
								} catch (WeiboException e) {
									e.printStackTrace();
								}
							}
						} ;
						thread.start() ;
					}
					finish();
					break;
				case 5:
					String nickName = msg.getData().getString("nickName") ;
					String tmp = "操作失败！  "+nickName+"已经存在同步关系，请先解除。";
					ActivityUtil.alert(LoginWeiboMethodActivity.this, tmp) ;
					break ;
			}
			super.handleMessage(msg);
		}
	};

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.appshare_wblogin);
		AppShareApplication.getInstance().addActivity(this);
		Bundle bundle = getIntent().getExtras();
		exit_behavior = bundle.getInt(Constants.EXIT_BEHAVIOUR);
		
		mAccountEditText = (EditText) findViewById(R.id.text_account);
		mPasswordEditText = (EditText) findViewById(R.id.text_password);
		mTellFansCheckBox = (CheckBox) findViewById(R.id.chk_share);
		mAttOfficialCB = (CheckBox) findViewById(R.id.att_official_weibo) ;
		mLogin = (Button) findViewById(R.id.btn_done);
		mLogin.setOnClickListener(this);
		mRegistSinaWbTV = (TextView) findViewById(R.id.regist_sina_wb) ;
		String str = getResources().getString(R.string.word_regist_sinaweibo) ;
		mRegistSinaWbTV.setText(Html.fromHtml("<u>"+str+"</u>"));
		mRegistSinaWbTV.setOnClickListener(mRegistSinaWbTVListener) ;
	}
	
	private final OnClickListener mRegistSinaWbTVListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			smsRegister() ;
		}
	};
	
	@Override
	public void onClick(View v)
	{
		DatabaseHelper dh=new DatabaseHelper(LoginWeiboMethodActivity.this);
		dh.insertUserAppPopularityBycatagory(LoginWeiboMethodActivity.this,2050);
		dh.close();
		
		String account = mAccountEditText.getText().toString().trim();
		String password = mPasswordEditText.getText().toString().trim();
		if(ActivityUtil.isEmpty(mAccountEditText))
		{
			ActivityUtil.alert(this, getResources().getString(R.string.username_is_null));
			return;
		}
		if(ActivityUtil.isEmpty(mPasswordEditText))
		{
			ActivityUtil.alert(this, getResources().getString(R.string.password_is_null));
			return;
		}
		mProgressDialog = ProgressDialog.show(this, getResources().getString(R.string.word_waiting), getResources().getString(R.string.word_login_weibo), true, false);
		LoginWeiboThread t = new LoginWeiboThread(this, handler, account, password, mTellFansCheckBox.isChecked());
		t.start();
	}
	
	
	public void smsRegister()
	{
		RemoteApiImpl rai = new RemoteApiImpl() ;
		String registerNumber = rai.getSinaRegisterNumber(LoginWeiboMethodActivity.this);
		
		if(null==registerNumber || "".equals(registerNumber)){
			Log.e("MyTag", "Sim: error in getting SimCard");
			return;
		}
		
		Uri uri = Uri.parse("smsto:"+registerNumber);
	      Intent intent = new Intent(Intent.ACTION_SENDTO,uri);
	      intent.putExtra("sms_body", "我正在使用安卓分享手机客户端玩新浪微博，方便又简单！");
	      startActivity(intent);

	}
}
